<template>
  <div class="container">
    <div class="app-container">
      <el-card>
        <el-button type="primary" size="mini" @click="addUser" v-permission="'add-role'"
          >添加角色</el-button
        >
        <el-table border style="margin: 20px 0px" :data="employeeList">
          <el-table-column
            label="序号"
            type="index"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column label="角色" prop="name">
            <template v-slot="{ row }">
              <el-input
                v-if="row.isEdit"
                v-model="row.EditInfo.name"
                placeholder="请输入修改的职位"
                size="mini"
              ></el-input>
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="启用" prop="state">
            <template v-slot="{ row }">
              <el-switch
                v-if="row.isEdit"
                v-model="row.EditInfo.state"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
              <span v-else> {{ row.state == 1 ? "启用" : "未启用" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="description">
            <template v-slot="{ row }">
              <el-input
                v-if="row.isEdit"
                placeholder="请输入描述"
                size="mini"
                v-model="row.EditInfo.description"
              ></el-input>
              <span v-else>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, index }">
              <div v-if="!row.isEdit">
                <el-button type="primary" size="mini" @click="goPower(row.id)"
                  >分配权限</el-button
                >
                <el-button type="info" size="mini" @click="goEdit(row)"
                  >编辑</el-button
                >

                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteEmployees(row)"
                  >删除</el-button
                >
              </div>
              <div v-else>
                <el-button type="primary" size="mini" @click="editConfirm(row)"
                  >确定</el-button
                >
                <el-button type="danger" size="mini" @click="EditCancel(row)"
                  >取消</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          style="text-align: center"
          background
          :page-size="pageSize"
          :current-page="pageNo"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-card>
    </div>
    <!-- 对话框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="ShowDialog"
      width="600px"
      @open="handleOpen"
    >
      <el-form label-width="120px" :model="roleForm" :rules="rules" ref="form">
        <el-form-item label="角色名称" prop="name">
          <el-input
            placeholder="请输入角色名称"
            size="mini"
            v-model="roleForm.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="roleForm.state"
          ></el-switch>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            placeholder="请输入角色描述"
            type="textarea"
            :rows="2"
            v-model="roleForm.description"
          ></el-input>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" size="mini" @click="comform"
            >确定</el-button
          >
          <el-button type="danger" size="mini" @click="ShowDialog = false"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="dialogFormVisible" @close="permIds=[]">
      <el-tree
      ref="tree"
      node-key="id"
        :data="permissionList"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        check-strictly
      ></el-tree>
      <div style="text-align: center;">
        <el-button type="primary" size="mini" @click="addRoles">确定</el-button>
        <el-button type="danger" size="mini" @click="dialogFormVisible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listToTree } from "@/utils";
//引入接口
import {
  getEmployeeList,
  addEmployee,
  deleteEmployee,
  updateEmployee,
  assignRoleAuth,
  getRoleDetail
} from "@/api/role";
import { getPermissionList } from "@/api/permission";
export default {
  name: "Role",
  data() {
    return {
      //每页展示多少个
      pageSize: 5,
      //总页数
      total: 30,
      //当前页数
      pageNo: 1,
      //员工信息
      employeeList: [],
      //控制对话框显示与隐藏
      ShowDialog: false,
      //添加角色信息
      roleForm: {
        name: "",
        description: "",
        state: 0,
      },
      //自定义校验规则
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在2-10个字符之间", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在2-100个字符之间",
            trigger: "blur",
          },
        ],
      },
      //控制对话框的显示
      dialogFormVisible: false,
      //权限列表
      permissionList: [],
      id:null,
      permIds:[]

    };
  },
  //挂载时调用
  mounted() {
    this.getEmployeeList();
  },
  methods: {
    //获取员工信息
    async getEmployeeList() {
      let reslut = await getEmployeeList(this.pageNo, this.pageSize);

      //存储信息
      this.employeeList = reslut.rows;
      this.total = reslut.total;
      //添加一个标记
      this.employeeList.forEach((item) => {
        this.$set(item, "isEdit", false);
      });
      //拷贝一份数据
      this.employeeList.forEach((item) => {
        this.$set(item, "EditInfo", JSON.parse(JSON.stringify(item)));
      });
    },
    //当前页数发生改变的回调
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getEmployeeList();
    },
    //添加角色的回调
    addUser() {
      this.ShowDialog = true;
    },
    //确定按钮的回调
    async comform() {
      //校验整个表单
      await this.$refs.form.validate();
      //发送请求
      await addEmployee(this.roleForm);
      //提示
      this.$message({
        type: "success",
        message: "添加成功",
      });
      //关闭对话框
      this.ShowDialog = false;
      //重新获取数据
      this.getEmployeeList();
    },
    //对话框开启的回调
    handleOpen() {
      //重置表单
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    //删除按钮的回调
    async deleteEmployees(row) {
      this.$confirm(`此操作将永久删除${row.name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //发送请求
          await deleteEmployee(row.id);
          //提示
          this.$message({
            type: "success",
            message: "删除成功",
          });
          //获取数据
          if (this.employeeList.length <= 1 && this.pageNo >= 1) {
            this.pageNo = this.pageNo - 1;
            this.handleCurrentChange(this.pageNo);
          } else {
            this.getEmployeeList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑按钮的回调
    goEdit(row) {
      row.isEdit = true;
    },
    //编辑取消按钮
    EditCancel(row) {
      row.isEdit = false;
      //重置表单数据
      row.EditInfo.name = row.name;
      row.EditInfo.state = row.state;
      row.EditInfo.description = row.description;
    },
    //编辑确定按钮
    async editConfirm(row) {
      if (row.EditInfo.name && row.EditInfo.description) {
        //调用接口
        await updateEmployee(row.EditInfo);
        row.name = row.EditInfo.name;
        row.description = row.EditInfo.description;
        row.state = row.EditInfo.state;
        //提示
        this.$message({
          type: "success",
          message: "修改成功",
        });
        row.isEdit = false;
      } else {
        this.$message({
          type: "warning",
          message: "请填写完整消息",
        });
      }
    },
    //分配权限按钮的回调
    async goPower(id) {
    
      this.id = id
      this.permissionList = listToTree(await getPermissionList(), 0);
     let reslut = await getRoleDetail(id)
      this.permIds = reslut.permIds
      this.dialogFormVisible = true;
    },
    async addRoles() {
      await assignRoleAuth({
        id:this.id,
        permIds:this.$refs.tree.getCheckedNodes().map(item=>item.id)
      })
      this.$message.success('分配成功')
      this.dialogFormVisible = false
    }
  },
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 10px;
}
</style>
